package net.feling.mcloud.filter;

import android.util.Log;

import net.feling.mcloud.entity.Message;
import net.feling.mcloud.entity.User;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Objects;

public class UserEncoder extends ProtocolEncoderAdapter {
    private Charset charset;

    public UserEncoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    public void encode(IoSession ioSession, Object message, ProtocolEncoderOutput output) throws Exception {
        IoBuffer ioBuffer = IoBuffer.allocate(100).setAutoExpand(true);
        CharsetEncoder charsetEncoder = charset.newEncoder();

        Message message1 = (Message) message;
        String type = message1.getType();
        String sender = message1.getSender();

        ioBuffer.putString(type + "\n", charsetEncoder);
        ioBuffer.putString(sender + "\n", charsetEncoder);

        if (type.equals(User.getType())) {

            System.out.println("进来了");
            User user = (User) message1.getContent();
            String uid = user.getUid();
            String CPUfreq = user.getCPUfreq();
            String memory = user.getMemory();
            String batteryLeft = user.getBatteryLeft();
            String GPSInfo = user.getGPSInfo();

            System.out.println(uid);

            ioBuffer.putString(uid + "\n", charsetEncoder);
            ioBuffer.putString(CPUfreq + "\n", charsetEncoder);
            ioBuffer.putString(memory + "\n", charsetEncoder);
            ioBuffer.putString(batteryLeft + "\n", charsetEncoder);
            ioBuffer.putString(GPSInfo + "\n", charsetEncoder);
        }

        if (type.equals("".getClass().getSimpleName())) {
            String content = (String) message1.getContent();
            Log.d("Command --->", content);
            ioBuffer.putString(content + "\n", charsetEncoder);
        }

        ioBuffer.flip();
        output.write(ioBuffer);
    }
}
